package com.sun.blog.sunblog.controller;

import com.sun.blog.sunblog.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Part;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * User: Songful
 * Date: 13-11-13-下午11:01
 */
@Controller
public class FileUploadController {

    @RequestMapping(value = "toUpload")
    public String toUpload() {
        return "upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView handleFileUplaod(@RequestParam("file1") MultipartFile file1) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;

        try {
            if (!file1.isEmpty()) {
                byte[] bytes = file1.getBytes();
                File newFile = new File("D:/mm.pdf");
                fos = new FileOutputStream(newFile);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);

            }
            User user = new User();
            user.setName("sss");
            return new ModelAndView("blogList",
                    (Map<String, Serializable>) new HashMap<String, Serializable>().put("me", user));
        } catch (IOException e) {
            e.printStackTrace();
            return new ModelAndView("redirect:toLogin.htm");
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }

        }
    }
}
